﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VisualAgile.Controllers;
using System.Web.Mvc;
using System.Web.Routing;
using VisualAgile.DTO;
using VisualAgile.DTO.Mappers;
using ProjectRouting.Controllers;
using System.Web.Security;
using System.Security.Principal;
using System.Web;
using VisualAgile.Web.Tests.Fakes;
using System.Collections;

namespace VisualAgile.Web.Tests
{
    /// <summary>
    /// Summary description for ProjectControllerTests
    /// </summary>
    [TestClass]
    public class ProjectControllerTests
    {
        public static ProjectController GetController()
        {
            VisualAgile.Controllers.LoginController.IFormsAuthentication formsAuth = new MockFormsAuthenticationService();
            MembershipProvider membershipProvider = new MockMembershipProvider();
            VisualAgile.Controllers.LoginController.AccountMembershipService membershipService = new VisualAgile.Controllers.LoginController.AccountMembershipService(membershipProvider);
            ProjectController controller = new ProjectController(formsAuth, membershipService);
            ControllerContext controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller);
            controller.ControllerContext = controllerContext;
            return controller;
        }

        [TestMethod]
        public void IndexAction_Should_Authenticate_Project_WithNullPassword_User_And_Return_ViewResult()
        {

            // Arrange
            var controller = GetController();

            // Act
            var result = controller.Index("demo123");

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }

        [TestMethod]
        public void IndexAction_Should_Not_Authenticate_Users_And_Return_ViewResult()
        {

            // Arrange
            var controller = GetController();

            // Act
            var result = controller.Index("someProject");

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));

            ViewResult data = result as ViewResult;

            //Should contains more than one user
            Assert.IsNotNull(data.ViewData["Users"], "No users found");

            //Should return for authenticate
            Assert.IsNotNull(data.ViewData["authenticate"], "User is authenticated");
        }

        [TestMethod]
        public void IndexAction_Should_Not_Authenticate_Project_WithNonNullPassword_User_And_Return_ViewResult()
        {

            // Arrange
            var controller = GetController();

            // Act
            var result = controller.Index("Default");

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));

            ViewResult data = result as ViewResult;

            //Should contains more than one user
            Assert.IsNull(data.ViewData["Users"], "More than one user found");

            //Should return for authenticate
            Assert.IsNotNull(data.ViewData["authenticate"], "User is authenticated");
        }

        [TestMethod]
        public void IndexAction_Should_Create_New_Project_And_Return_ViewResult()
        {

            // Arrange
            var controller = GetController();

            // Act
            var result = controller.Index("demo123");

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));
        }       

        public class MockFormsAuthenticationService : VisualAgile.Controllers.LoginController.IFormsAuthentication
        {
            public void SignIn(string userName, bool createPersistentCookie)
            {
            }

            public void SignOut()
            {
            }
        }

        public class MockIdentity : IIdentity
        {
            public string AuthenticationType
            {
                get
                {
                    return "MockAuthentication";
                }
            }

            public bool IsAuthenticated
            {
                get
                {
                    return true;
                }
            }

            public string Name
            {
                get
                {
                    return "someUser";
                }
            }
        }

        public class MockPrincipal : IPrincipal
        {
            IIdentity _identity;

            public IIdentity Identity
            {
                get
                {
                    if (_identity == null)
                    {
                        _identity = new MockIdentity();
                    }
                    return _identity;
                }
            }

            public bool IsInRole(string role)
            {
                return false;
            }
        }

        public class MockMembershipUser : MembershipUser
        {
            public override bool ChangePassword(string oldPassword, string newPassword)
            {
                return newPassword.Equals("newPass");
            }
        }

        public class MockHttpContext : HttpContextBase
        {
            private IPrincipal _user;
            private IDictionary _items;

            public override IPrincipal User
            {
                get
                {
                    if (_user == null)
                    {
                        _user = new MockPrincipal();
                    }
                    return _user;
                }
                set
                {
                    _user = value;
                }
            }

            public override HttpSessionStateBase Session
            {
                get
                {
                    return null;
                }
            }

            public override IDictionary Items
            {
                get
                {
                    if (_items == null)
                    {
                        AllManagerFactory manager = new AllManagerFactory()
                        {
                            UserManager = new FakeUserManager(
                                    FakeUserData.CreateTestUsers()
                            ),
                            ProjectManager = new FakeProjectManager(
                                FakeProjectData.CreateTestProjects()
                            ),
                            RoleManager = new FakeRoleManager(
                                FakeRoleData.CreateTestRoles()
                            ),
                            ActualsManager = new FakeActualManager(
                                FakeActualData.CreateTestActual()
                            ),
                            FeatureManager = new FakeFeatureManager(
                                FakeFeatureData.CreateTestFeatures()
                            ),
                            FeelingManager = new FakeFeelingsManager(
                                FakeFeelingsData.CreateTestFeelingss()
                            ),
                            IterationManager = new FakeIterationManager(
                                FakeIterationData.CreateTestIterations()
                            ),
                            LabelManager = new FakeLabelManager(
                                FakeLabelData.CreateDemoLabels()
                            ),
                            ReleaseManager = new FakeReleaseManager(
                                FakeReleaseData.CreateTestReleases()
                            ),
                            StatusManager = new FakeStatusManager(
                                FakeStatusData.CreateTestStatuss()
                            ),
                            StoryManager = new FakeStoryManager(
                                FakeStoryData.CreateTestStorys()
                            ),
                            TaskManager = new FakeTaskManager(
                                FakeTaskData.CreateTestTasks()
                            )                            
                        };

                        _items = new Dictionary<string, AllManagerFactory>();
                        _items.Add("ManagerFactory", manager);
                    }

                    return _items;
                }
            }
        }

        public class MockMembershipProvider : MembershipProvider
        {
            string _applicationName;

            public override string ApplicationName
            {
                get
                {
                    return _applicationName;
                }
                set
                {
                    _applicationName = value;
                }
            }

            public override bool EnablePasswordReset
            {
                get
                {
                    return false;
                }
            }

            public override bool EnablePasswordRetrieval
            {
                get
                {
                    return false;
                }
            }

            public override int MaxInvalidPasswordAttempts
            {
                get
                {
                    return 0;
                }
            }

            public override int MinRequiredNonAlphanumericCharacters
            {
                get
                {
                    return 0;
                }
            }

            public override int MinRequiredPasswordLength
            {
                get
                {
                    return 6;
                }
            }

            public override string Name
            {
                get
                {
                    return null;
                }
            }

            public override int PasswordAttemptWindow
            {
                get
                {
                    return 3;
                }
            }

            public override MembershipPasswordFormat PasswordFormat
            {
                get
                {
                    return MembershipPasswordFormat.Clear;
                }
            }

            public override string PasswordStrengthRegularExpression
            {
                get
                {
                    return null;
                }
            }

            public override bool RequiresQuestionAndAnswer
            {
                get
                {
                    return false;
                }
            }

            public override bool RequiresUniqueEmail
            {
                get
                {
                    return false;
                }
            }

            public override bool ChangePassword(string username, string oldPassword, string newPassword)
            {
                throw new NotImplementedException();
            }

            public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
            {
                throw new NotImplementedException();
            }

            public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, Object providerUserKey, out MembershipCreateStatus status)
            {
                MockMembershipUser user = new MockMembershipUser();

                if (username.Equals("someUser") && password.Equals("goodPass") && email.Equals("email"))
                {
                    status = MembershipCreateStatus.Success;
                }
                else
                {
                    // the 'email' parameter contains the status we want to return to the user
                    status = (MembershipCreateStatus)Enum.Parse(typeof(MembershipCreateStatus), email);
                }

                return user;
            }

            public override bool DeleteUser(string username, bool deleteAllRelatedData)
            {
                throw new NotImplementedException();
            }

            public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override int GetNumberOfUsersOnline()
            {
                throw new NotImplementedException();
            }

            public override string GetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }

            public override string GetUserNameByEmail(string email)
            {
                throw new NotImplementedException();
            }

            public override MembershipUser GetUser(Object providerUserKey, bool userIsOnline)
            {
                throw new NotImplementedException();
            }

            public override MembershipUser GetUser(string username, bool userIsOnline)
            {
                return new MockMembershipUser();
            }

            public override string ResetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }

            public override bool UnlockUser(string userName)
            {
                throw new NotImplementedException();
            }

            public override void UpdateUser(MembershipUser user)
            {
                throw new NotImplementedException();
            }

            public override bool ValidateUser(string username, string password)
            {
                return password.Equals("goodPass");
            }

        }
    }
}
